package net.dwade.loader;

import net.dwade.loader.config.DynamicReloadContext;
import net.dwade.loader.config.EnableDynamicReloader;
import net.dwade.loader.service.AppRecommendService;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.file.Paths;
import java.util.Collections;

@SpringBootApplication
@EnableDynamicReloader
public class LoaderApplication {

	public static void main(String[] args) throws Throwable {

		ApplicationContext context = SpringApplication.run( LoaderApplication.class, args );

		// 调用默认的算法版本，实际应用中，可以将算法的默认实现配置在db中
		AppRecommendService recommendService = context.getBean(AppRecommendService.class);
		recommendService.recommend("123412341324", Collections.EMPTY_LIST);

		DynamicReloadContext dynamicReloadContext = context.getBean(DynamicReloadContext.class);

		// 模拟线上服务，对算法进行热插拔
		String originalClassName = "net.dwade.loader.service.impl.DefaultAppRecommendService";
		String newClassName = "net.dwade.loader.service.impl.AppRecommenServiceV1";
		URL jarFile = LoaderApplication.class.getResource("/dynamic-loader-demo.RELEASE.1.0.0.jar");
		dynamicReloadContext.load(jarFile, newClassName, originalClassName );

		// 这里还是调用原来的bean，只不过最终的实现类变了
		recommendService.recommend("123412341324", Collections.EMPTY_LIST);

		// 模拟线上服务，对算法进行热插拔
		originalClassName = "net.dwade.loader.service.impl.DefaultAppRecommendService";
		newClassName = "net.dwade.loader.service.impl.AppRecommenServiceV2";
		jarFile = LoaderApplication.class.getResource("/dynamic-loader-demo.RELEASE.1.0.1.jar");
		dynamicReloadContext.load(jarFile, newClassName, originalClassName );

		// 这里还是调用原来的bean，只不过最终的实现类变了
		recommendService.recommend("123412341324", Collections.EMPTY_LIST);

	}

}
